/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mapfinal.server.auth.web;

import java.util.List;

import javax.servlet.http.HttpSession;

import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.web.RequestManager;
import com.lambkit.web.directive.LambkitDirective;
import com.mapfinal.server.auth.AuthLoginCache;
import com.mapfinal.server.auth.model.AuthJob;
import com.mapfinal.server.auth.model.AuthOrganization;
import com.mapfinal.server.auth.model.AuthRule;
import com.mapfinal.server.auth.model.Role;
import com.mapfinal.server.auth.model.User;

/**
 * Auth标签, 用户的信息，role， organization，rule， job<br>
 * 返回值：{entity信息}
 * @author lambkit
 */
public class AuthDirective extends LambkitDirective {

	@Override
	public void onRender(Env env, Scope scope, Writer writer) {
		// TODO Auto-generated method stub
		String type = getPara("type", scope);
		String tagEntityKeyname = getPara("key", scope, "entity");
		HttpSession session = RequestManager.me().getRequest().getSession(false);
		System.out.println("auth session: " + session.getId());
		String userName = session != null ? (String)session.getAttribute("user") : null;
		System.out.println("auth: " + userName);
		User user = AuthLoginCache.getLoginUser(userName);
		if(user==null) {
			scope.set(tagEntityKeyname, null);
		} else if("role".equals(type)) {
			List<Role> roles = Role.service().getRoles(user.getId());
			scope.set(tagEntityKeyname, roles);
		} else if("organization".equals(type)) {
			List<AuthOrganization> orgs = AuthOrganization.service().getOrganizations(user.getId());
			scope.set(tagEntityKeyname, orgs);
		} else if("rule".equals(type)) {
			List<AuthRule> rules = AuthRule.service().getPermissions(user.getId());
			scope.set(tagEntityKeyname, rules);
		} else if("job".equals(type)) {
			List<AuthJob> jobs = AuthJob.service().getJobs(user.getId());
			scope.set(tagEntityKeyname, jobs);
		} else {
			scope.set(tagEntityKeyname, user);
		}
        renderBody(env, scope, writer);
	}

	@Override
	public boolean hasEnd() {
		return true;
	}
}
